from Spider import spide
import json
import time
import random

def loadFile(fname, header):
	value = []
	stocks = []
	count = 0
	with open(fname, "r") as file:
		for each in file:
			each = each.replace("\n", "")
			stocks.append(each)

	totleLen = len(stocks)
	for i in range(totleLen):
		each = stocks[i]
		count += 1
		if count >= 20:
			print("%d/%d [%s]\r" % (i, totleLen, int(20 * (i / totleLen)) * "#" + int(20 * (1 - i / totleLen)) * "-"), end="")
		
		try:
			res = spide(header + each)
			res = json.loads(res)
			pe = res['data']['quote']['pe_forecast']
			pb = res['data']['quote']['pb']
			market_capital = res['data']['quote']['market_capital']
			value.append({"id":header + each, "pe": pe, "pb": pb, "market_capital": market_capital})
		except Exception as e:
			print(e)

		if count >= 20:
			time.sleep(random.random() / 5)
			count = 0
	return value


def alayse(stocks):
	market_capital = 0
	assets = 0
	profit = 0

	for each in stocks:
		market_capital += each["market_capital"]
		assets += each["market_capital"] / each['pb']
		profit += each["market_capital"] / each['pe']
	
	return {"assets": assets, "profit": profit, "capital": market_capital}

def showDetail(res, resName):
	hundred_million = 100000000
	print("%s: \n\t总市值(亿元):%.2f,\t总资产(亿元):%.2f\n\t总利润(亿元):%.2f" % (resName, res["capital"] / hundred_million, res["assets"] / hundred_million, res["profit"] / hundred_million), end="")
	print("\n\t市净率(PB):%.2f,\t市盈率(PE): %.2f\n\t净资产收益率(ROE): %.4f" % (res["pb"], res["pe"], res["pb"] / res["pe"]))

def alayseAll():
	sh = loadFile("上交所.txt", "SH")
	sz = loadFile("深交所.txt", "SZ")

	sh_res = alayse(sh)
	sz_res = alayse(sz)
	totle_res = {"assets": sh_res["assets"] + sz_res["assets"], "profit": sh_res["profit"] + sz_res["profit"], "capital": sh_res["capital"] + sz_res["capital"]}

	sh_res["pb"] = sh_res["capital"] / sh_res["assets"]
	sh_res["pe"] = sh_res["capital"] / sh_res["profit"]

	sz_res["pb"] = sz_res["capital"] / sz_res["assets"]
	sz_res["pe"] = sz_res["capital"] / sz_res["profit"]

	totle_res["pb"] = totle_res["capital"] / totle_res["assets"]
	totle_res["pe"] = totle_res["capital"] / totle_res["profit"]
	
	showDetail(sh_res, "上交所")
	showDetail(sz_res, "深交所")
	showDetail(totle_res, "A股")


if __name__ == "__main__":
	alayseAll()
